module.exports = (app) => {
    const router = app.router;

    const Good = app.models.Good;


    router.get('/goods', function* () {
        const query = this.query;

        const goods = yield Good.query(qb => {
            qb.where('deleted', Good.NOT_DELETED);

            if(query.q) {
                qb.where(function() {
                    this.where('name', 'like', `%${query.q}%`)
                    .orWhere('code', 'like', `%${query.q}%`);
                });
            }
        })
        .fetchItems({
            page_size: query.page_size,
            page_num: query.page_num
        }, {
            withRelated: ['category', 'parentCategory']
        });

        this.body = goods;
    });

    router.post('/goods', function * () {
        const body = this.request.body;

        const check = yield Good.query(qb => {
            qb.where('name', body.name)
            .orWhere('code', body.code);
            qb.where('deleted', Good.NOT_DELETED);
        })
        .fetch();

        if(check) {
            this.throw(400, '该物品已存在');
        }

        const good = Good.safeForge(body);

        yield good.save();

        this.body = body;
    });

    router.put('/goods/:id', function * () {
        const body = this.request.body;

        let good = yield Good.where({
            id: this.params.id
        })
        .fetch({
            require: true
        });

        const check = yield Good.query(qb => {
            qb.where('name', body.name)
            .orWhere('code', body.code);
            qb.where('deleted', Good.NOT_DELETED);
        })
        .fetch();

        if(check && good.get('id') !== +this.params.id) {
            this.throw(400, '该物品已存在');
        }

        delete body.users;
        delete body.category;
        delete body.parentCategory;

        good.safeSet(body);

        yield good.save();

        this.body = good;
    });

    router.delete('/goods/:id', function *() {
        let batch = yield Good.where({
            id: this.params.id
        })
        .fetch({
            require: true
        });

        batch.set('deleted', Good.DELETED);

        yield batch.save();

        this.body = this.params;
    });
};
